﻿using NHibernate;
using System;

namespace DataLayer.UoW
{
    public class UnitOfWorkFactory : IUnitOfWorkFactory
    {
        private static ISession currentSession;

        internal UnitOfWorkFactory()
        {
        }

        public IUnitOfWork Create()
        {
            ISession session = CreateSession();
            session.FlushMode = FlushMode.Commit;
            currentSession = session;
            return new UnitOfWorkImplementor(this, session);
        }

        private ISession CreateSession()
        {
            return SessionProvider.GetSession();
        }

        public ISession CurrentSession
        {
            get
            {
                if (currentSession == null)
                {
                    log4net.LogManager.GetLogger(GetType()).Error("You are not in a unit of work.");
                    throw new InvalidOperationException("You are not in a unit of work.");
                }
                return currentSession;
            }
            set { currentSession = value; }
        }

        public void DisposeUnitOfWork(UnitOfWorkImplementor adapter)
        {
            CurrentSession = null;
            UnitOfWork.DisposeUnitOfWork(adapter);
        }

    }
}
